package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utlis.SMSUtils;
import com.itheima.reggie.utlis.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {

   @Autowired
   private UserService userService;

    /**
     * 发生手机短信验证码
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user , HttpServletRequest request){
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)){

            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);

            SMSUtils.sendMessage(phone,code);

            request.getSession().setAttribute(user.getPhone(),code);
            return R.success("手机验证码短信发送成功");
        }
        return R.success("短信发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpServletRequest request){
        log.info(map.toString());
        String phone = map.get("phone").toString();

        String code = map.get("code").toString();

        Object codeInSession = request.getSession().getAttribute(phone);

        if (codeInSession!=null && codeInSession.equals(code)){

            LambdaQueryWrapper<User>queryWrapper=new LambdaQueryWrapper<>();

            queryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(queryWrapper);
            if (user==null){
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            request.getSession().setAttribute("user",user.getId());
            return  R.success(user);
        }
        return R.error("登录失败");
    }
}
